package com.itheima.controller;


import com.itheima.common.CommonResult;
import com.itheima.dto.PhoneCodeDto;
import com.itheima.dto.PhoneDto;
import com.itheima.service.UserService;
import com.itheima.vo.LoginVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;

@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {

    @Autowired
    private UserService userService;


    @PostMapping("/sendMsg")
    public CommonResult sendMsg(@RequestBody PhoneDto phoneDto) {

        boolean res = userService.sendMsg(phoneDto.getPhone());

        return new CommonResult(res ? 200 : 500, res ? "发送成功" : "发送失败", null);

    }


    @PostMapping("/login")
    public CommonResult login(@RequestBody PhoneCodeDto phoneCodeDto) {
        LoginVo login = userService.login(phoneCodeDto);
        return CommonResult.success("登录成功", login);
    }

    @PostMapping("/loginout")
    public CommonResult logout(HttpServletRequest request) {
        String token = request.getHeader("AuthorizationUser");//拿到请求头
        if (StringUtils.hasText(token)) {
            userService.clearToken(token);
        }
        return CommonResult.success("退出登录成功");
    }

}
